<?php

class XosoController extends WebController
{
    public function init(){
        parent::init();
        Yii::import('ext.simple_html_dom');
        Yii::import('ext.XML2Array');
    }

    public function actionAjax(){
        error_reporting(0);
        //set_time_limit(1);
        list($date, $results, $results2, $db) = $this->_getKetqua888();
        $this->renderPartial('content', array(
            'date' => $date,
            'results' => $results,
            'results2' => $results2,
            'db' => $db,
        ));  
    }

    public function actionIndex(){
        list($date, $results, $results2, $db) = $this->_getKetqua888();
    
        if(Yii::app()->request->getQuery('test')){
            echo '<pre>DB: ';print_r($db);echo '<pre>';
            echo '<pre>RESULT: ';print_r($results);echo '<pre>';
            echo '<pre>RESULT2: ';print_r($results2);echo '<pre>';die; 
        }
        
        $this->pageTitle = "Kết quả xổ số trực tiếp";
        $this->pageDesc = "Tường thuật trực tiếp kết quả xổ xố nhanh trong ngày";
        
        $this->render('index', array(
            'date' => $date,
            'results' => $results,
            'results2' => $results2,
            'db' => $db,
        ));    
    }
   
    private function _group($results){
        $data = array(
            0 => array(), 
            1 => array(), 
            2 => array(), 
            3 => array(), 
            4 => array(), 
            5 => array(), 
            6 => array(), 
            7 => array(), 
            8 => array(), 
            9 => array(), 
        );
        foreach($results as $r){
            $t = substr($r, -2);
            $f = substr($t, 0, 1);
            $l = substr($t, 1, 1);
            if(is_numeric($f))
                $data[$f][] = $l;
        }
        return $data;
    }
    
    private function _getKetqua888(){
        error_reporting(0);
        $url = 'http://ketqua888.com/xml/live_MB.xml';
        $html = new simple_html_dom($url);

        $array = XML2Array::createArray($html->innertext);
        $datas = $array['ketqua888']['xsmb']['giai'];
        $date = $array['ketqua888']['xsmb']['@attributes']['date'];
        
        $results = array();
        foreach($datas as $data){
            $results[] = $data['@attributes']['value'];   
        }
        $results2 = $this->_group($results);
          
        $db['db'] = substr($results[0], -2);
        $db['dbf'] = substr($db['db'], 0, 1);
        $db['dbl'] = substr($db['db'], 1, 1);
        
        return array($date, $results, $results2, $db);   
    }
    
    private function _getKetquanet(){
        $url = 'http://ketqua.net/xo-so/kqauto/kqmb.html';
        
    }
    private function _getXosocomvn(){
        $url = 'http://www.xoso.com.vn/Modules/lotos/ShowKQOnlineII.aspx';
        
    }
}